#import "SMRRatingView.h"
#import "SMRRatingCell.h"


@interface SMRRatingView (SMRRatingViewPrivateMethods)
-(void)incrementRating_;
-(void)decrementRating_;
@end


#pragma mark -
@implementation SMRRatingView

+(Class)cellClass {
	return [SMRRatingCell class];
}

-(BOOL)acceptsFirstResponder {
	return YES;
}


#pragma mark -
#pragma mark Accessors

-(void)setAllowsHalfStars:(BOOL)shouldAllow {
	[(SMRRatingCell *)[self cell] setAllowsHalfStars:shouldAllow];
}

-(BOOL)allowsHalfStars {
	return [(SMRRatingCell *)[self cell] allowsHalfStars];
}

-(void)setRatingColor:(NSColor *)aColor {
    [(SMRRatingCell *)[self cell] setRatingColor:aColor];
}

-(NSColor *)ratingColor {
    return [(SMRRatingCell *)[self cell] ratingColor];
}


#pragma mark -
#pragma mark Event handling

-(void)keyDown:(NSEvent *)theEvent {
	if ([theEvent modifierFlags] & NSNumericPadKeyMask)
		[self interpretKeyEvents:[NSArray arrayWithObject:theEvent]];
	else 
		[super keyDown:theEvent];
}

-(void)mouseDown:(NSEvent *)theEvent {
	NSWindow *window = [self window];
	NSResponder *firstResponder = [window firstResponder];
	if (self == firstResponder)
		[super mouseDown:theEvent];
	else 
		[window makeFirstResponder:self];
}

-(void)moveLeft:(id)sender {
	[self decrementRating_];
}

-(void)moveRight:(id)sender {
	[self incrementRating_];
}

-(void)moveUp:(id)sender {
	[self incrementRating_];
}

-(void)moveDown:(id)sender {
	[self decrementRating_];
}


#pragma mark -
#pragma mark Private

-(void)incrementRating_ {
	double rating = [[[self cell] objectValue] doubleValue];
	if (rating >= [self maxValue]) {
		NSBeep();
		return;
	}
	rating += [self allowsHalfStars] ? 0.5 : 1.0;
	[[self cell] setDoubleValue:rating];
	[self sendAction:[self action] to:[self target]];
	[self setNeedsDisplay:YES];
}

-(void)decrementRating_ {
	double rating = [[[self cell] objectValue] doubleValue];
	if (rating <= 0) {
		NSBeep();
		return;
	}
	rating -= [self allowsHalfStars] ? 0.5 : 1.0;
	[[self cell] setDoubleValue:rating];
	[self sendAction:[self action] to:[self target]];
	[self setNeedsDisplay:YES];
}

@end
